﻿using LY.Manage.DALFactory;
using LY.Manage.IDAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LY.Manage.BLL
{
    //在业务基类中完成DbSession的调用,然后将业务中公共的方法定义在基类中,
    //但这些方法不知道通过DbSession来获取那个数据操作类的实例。
    //所以讲该业务基类定义成抽象类，加上一个抽象方法,加上一个IBaseDal属性,
    //并且让基类的构造方法调用抽象方法目的是在表现层new 具体的业务子类,父类的构造方法被调用
    //这时执行抽象方法,但执行的是子类里面具体的实现,业务子类知道通过
    //DBSession获取拿个数据操作类的实例
    public abstract class BaseService<T> where T:class ,new()
    {
        //业务层要调用DbSession
        public IDBSession  CurrentDbSession
        {
            get
            {
                //暂时先new 
                //return new DBSession();
                return DBSessionFactory.CreateDBSession();
            }
        }

        public IDAL.IBaseDal<T> CurrentDal { get; set; }
        public abstract void SetCurrentDal();
        public BaseService()
        {
            SetCurrentDal();    //子类一定要实现抽象方法
        }

        public IQueryable<T> LoadEntities(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda)
        {
            // CurrentDbSession.UesrInfoDal.LoadEntities(whereLambda);

            return CurrentDal.LoadEntities(whereLambda);
        }

        public IQueryable<T> LoadPageEntities<s>(int pageIndex, int pageSize, out int totalCount, System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, s>> orderLambda, bool isAsc)
        {
            return CurrentDal.LoadPageEntities(pageIndex, pageSize,out totalCount, whereLambda, orderLambda, isAsc);
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool DeleteEntity(T entity)
        {
            //在数据层并没有调用SaveChanges方法,只是添加到EF上下文,所以这里调用保存
            CurrentDal.DeleteEntity(entity);
            return CurrentDbSession.SaveChanges();
        }
        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool UpdateEntity(T entity)
        {
            CurrentDal.UpdateEntity(entity);
            return CurrentDbSession.SaveChanges();
        }
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public T AddEntity(T entity)
        {
            CurrentDal.AddEntity(entity);
            CurrentDbSession.SaveChanges();
            return entity;
        }


    }
}
